from PyQt5.QtWidgets import QWidget, QVBoxLayout, QLabel, QHBoxLayout
from PyQt5.QtCore import Qt, QPoint
from PyQt5.QtGui import QFont, QPixmap
from qfluentwidgets import SmoothScrollArea, PrimaryPushButton, InfoBar, InfoBarPosition
import json
import os
from run_experiments import run_path_planning


class HoverMoveButton(PrimaryPushButton):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.original_pos = self.pos()
        self.move_offset = QPoint(5, 5)  # 向右下角移动的偏移量

    def enterEvent(self, event):
        self.original_pos = self.pos()
        self.move(self.pos() + self.move_offset)
        super().enterEvent(event)

    def leaveEvent(self, event):
        self.move(self.original_pos)
        super().leaveEvent(event)


class PlanningInterface(SmoothScrollArea):
    def __init__(self, parent=None):
        super().__init__(parent=parent)
        self.view = QWidget(self)
        self.vBoxLayout = QVBoxLayout(self.view)
        self.setWidget(self.view)
        self.setWidgetResizable(True)

        # 将背景样式直接应用到主视图
        self.view.setStyleSheet('''
            QWidget#mainView {
                border-image: url(pic/background2.png) 0 0 0 0 stretch stretch;
            }
        ''')
        self.view.setObjectName("mainView")

        # 添加中间层图片
        self.bg_image = QLabel(self.view)
        self.bg_image.setPixmap(QPixmap("pic/lujingguihua.png"))
        self.bg_image.setScaledContents(True)  # 允许图片缩放
        self.bg_image.setStyleSheet('background: transparent;')
        self.bg_image.lower()  # 将图片置于底层，但在背景之上

        # 确保滚动区域和其他组件保持透明
        self.setStyleSheet('''
            QScrollArea {
                border: none;
                background: transparent;
            }
            QLabel {
                background: transparent;
                color: white;
            }
            QPushButton {
                border: none;
                background-color: transparent;
            }
        ''')

        self.initUI()

    def initUI(self):
        self.vBoxLayout.setAlignment(Qt.AlignCenter)
        self.vBoxLayout.setSpacing(60)  # 增大控件间距

        # 增加顶部空白，将整体内容向下移动40%
        self.vBoxLayout.addSpacing(400)  # 从150增加到400

        # 删除标题相关代码

        # 添加说明文本，增大字号
        description = QLabel('本功能将执行路径规划算法\n请确保已完成象限处理步骤')
        description.setFont(QFont("Microsoft YaHei", 14))
        description.setAlignment(Qt.AlignCenter)
        self.vBoxLayout.addWidget(description)

        # 增加说明文本和状态标签之间的间距
        self.vBoxLayout.addSpacing(60)

        # 添加状态标签，增大字号
        self.status_label = QLabel('准备就绪...')
        self.status_label.setFont(QFont("Microsoft YaHei", 14))
        self.status_label.setAlignment(Qt.AlignCenter)
        self.vBoxLayout.addWidget(self.status_label)

        # 增加状态标签和按钮之间的间距
        self.vBoxLayout.addSpacing(100)

        # 添加规划按钮，使用水平布局确保居中
        button_layout = QHBoxLayout()
        button_layout.setAlignment(Qt.AlignCenter)

        # 修改按钮样式使用背景图片
        self.plan_button = HoverMoveButton('')  # 使用自定义的悬停移动按钮
        pixmap = QPixmap("pic/kaishilujingguihua.png")
        self.plan_button.setFixedSize(pixmap.size())  # 设置按钮大小与图片一致
        self.plan_button.setStyleSheet('''
            PrimaryPushButton {
                border: none;
                background-image: url(pic/kaishilujingguihua.png);
                background-position: center;
                background-repeat: no-repeat;
                background-color: transparent;
            }
            PrimaryPushButton:hover {
                background-color: transparent;
            }
            PrimaryPushButton:pressed {
                background-color: transparent;
            }
        ''')
        self.plan_button.clicked.connect(self.start_planning)
        button_layout.addWidget(self.plan_button)

        self.vBoxLayout.addLayout(button_layout)

        # 添加底部弹性空间
        self.vBoxLayout.addStretch()

    def start_planning(self):
        try:
            self.status_label.setText('正在进行路径规划...')
            self.plan_button.setEnabled(False)

            current_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
            data_dir = os.path.join(current_dir, "data")

            total_cost = 0  # 总成本（路径长度）
            successful_paths = 0  # 成功规划的路径数量
            total_requested = 0  # 总请求的点对数

            # 对每个象限进行路径规划
            for i in range(1, 5):
                quadrant_file = os.path.join(data_dir, f"quadrant_{i}.txt")
                if not os.path.exists(quadrant_file):
                    continue

                try:
                    print(f"\n处理象限 {i}...")
                    result, requested_paths, path_cost = run_path_planning(quadrant_file, "CBS")
                    total_requested += requested_paths

                    if result and result.get('paths'):
                        total_cost += path_cost
                        successful_paths += len(result['paths'])

                        # 直接生成该象限的动画数据
                        animation_file = os.path.join(data_dir, f"quadrant_{i}.animation.json")
                        with open(animation_file, 'w', encoding='utf-8') as f:
                            animation_data = {
                                "map": [[bool(cell) for cell in row] for row in result['map']],
                                "starts": [list(start) for start in result['starts']],
                                "goals": [list(goal) for goal in result['goals']],
                                "paths": [[list(pos) for pos in path] for path in result['paths']]
                            }
                            json.dump(animation_data, f, indent=2)
                        print(f"已保存象限{i}的动画数据")

                except Exception as e:
                    print(f"象限{i}规划错误: {str(e)}")
                    continue

            # 统计和显示结果
            if successful_paths > 0:
                status_text = (f'规划完成!\n'
                               f'路径规划成功率: {successful_paths}/{total_requested}\n'
                               f'总成本(路径长度): {total_cost}')
                self.status_label.setText(status_text)

                # 将统计结果写入文件
                result_file = os.path.join(data_dir, "total_cost.txt")
                with open(result_file, 'a', encoding='utf-8') as f:
                    f.write(f"{total_requested},{total_cost}\n")

                InfoBar.success(
                    title='成功',
                    content=f'路径规划完成 ({successful_paths}/{total_requested} 条路径)',
                    orient=Qt.Horizontal,
                    isClosable=True,
                    position=InfoBarPosition.TOP,
                    duration=2000,
                    parent=self
                )
            else:
                raise Exception("所有路径规划都失败了")

        except Exception as e:
            self.status_label.setText('规划失败!')
            InfoBar.error(
                title='错误',
                content=f'路径规划出错: {str(e)}',
                orient=Qt.Horizontal,
                isClosable=True,
                position=InfoBarPosition.TOP,
                duration=4000,
                parent=self
            )
        finally:
            self.plan_button.setEnabled(True)

    def resizeEvent(self, event):
        """重写调整大小事件以确保图片始终填满界面"""
        super().resizeEvent(event)
        self.bg_image.setGeometry(0, 0, self.view.width(), self.view.height())
